package com.kin207.netty.tcp;

import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kin207.netty.server.IChannelHandlerInitializer;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.concurrent.EventExecutorGroup;

public class TcpChannelInitializer extends ChannelInitializer<SocketChannel> {
	final static Logger logger = LoggerFactory.getLogger(TcpChannelInitializer.class);
	
	private EventExecutorGroup eventExecutorGroup;
	private IChannelHandlerInitializer channelHandlerInitializer;
	private Map<String, ChannelHandler> initHandles;
	
	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		logger.debug("add channel handlers begin...");
		if(channelHandlerInitializer!=null){
			channelHandlerInitializer.channelHandlerInitializer(pipeline);
		}
		if(initHandles!=null){
			for(Entry<String, ChannelHandler> handle : initHandles.entrySet()){
				if('@'==handle.getKey().charAt(0)){
					pipeline.addLast(eventExecutorGroup, handle.getKey().substring(1), handle.getValue());
					logger.debug("add EventExecutorGroup channel handlers, eventExecutorGroup:{} key:{}, handler class:{}", eventExecutorGroup, handle.getKey(), handle.getValue().getClass());
				}else{
					pipeline.addLast(handle.getKey(), handle.getValue());
					logger.debug("add channel handlers, key:{}, handler class:{}", handle.getKey(), handle.getValue().getClass());
				}
			}
		}
		logger.debug("add channel handlers end.");
	}
	

	public Map<String, ChannelHandler> getInitHandles() {
		return initHandles;
	}

	public void setInitHandles(Map<String, ChannelHandler> initHandles) {
		this.initHandles = initHandles;
	}


	public IChannelHandlerInitializer getChannelHandlerInitializer() {
		return channelHandlerInitializer;
	}


	public void setChannelHandlerInitializer(IChannelHandlerInitializer channelHandlerInitializer) {
		this.channelHandlerInitializer = channelHandlerInitializer;
	}


	public EventExecutorGroup getEventExecutorGroup() {
		return eventExecutorGroup;
	}


	public void setEventExecutorGroup(EventExecutorGroup eventExecutorGroup) {
		this.eventExecutorGroup = eventExecutorGroup;
	}
	
	
}
